package com.estagio.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;


public abstract class Dao<T> {
	
	private Session sessao;	
	private Transaction transaction;

	public Session getSessao() {
		return sessao;
	}

	public void setSessao(Session sessao) {
		this.sessao = sessao;
	}
	
	

	public Transaction getTransaction() {
		return transaction;
	}

	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
	}

	public void save(Object obj) {
		this.sessao = HibernateUtil.getSession().getCurrentSession();
		this.sessao.save(obj);

	}
	
	public void update(Object obj) {
		this.sessao = HibernateUtil.getSession().getCurrentSession();
		this.sessao.merge(obj);
		this.sessao.flush();
		this.sessao.refresh(obj);
	}
	
	public void delete(Object obj) {
		this.sessao = HibernateUtil.getSession().openSession();
		this.transaction = this.sessao.beginTransaction();
		this.sessao.delete(obj);
		this.transaction.commit();
		this.sessao.close();
	}	
	
	protected void addRestrictionIfNotNull(Criteria criteria, String propertyName, Object value) {
	    if (value != null) {
	    	if(value instanceof String) {
	    		String str = (String) value;
	    		criteria.add(Restrictions.like(propertyName, str, MatchMode.ANYWHERE).ignoreCase());
	    	} else {
		        criteria.add(Restrictions.eq(propertyName, value));
	    	}
	    }
	}
	
	public abstract List<T> find(Object obj);
	public abstract List<T> findByPrimaryKey(Object obj);
	public abstract List<T> list();


}
